package com.bulletelc.apollopre.module.main.center.setting.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.framework.BaseActivity;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.widget.FoolBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by CX on 2018/1/22.
 */

public class ModifyProfileActivity extends BaseActivity implements View.OnClickListener ,FoolBar.ClickCallback{

    private EditText etNickName;
    private Button btnSave;
    private FoolBar foolBar;

    @Override
    public int getLayoutRes() {
        return R.layout.modify_profile_activity;
    }

    @Override
    public void assignViews() {
        etNickName = findViewById(R.id.et_nick_name);
        btnSave = findViewById(R.id.btnSave);
        foolBar = findViewById(R.id.flBar);
    }

    @Override
    public void setListener() {
        foolBar.setClickCallback(this);
        btnSave.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        foolBar.setTitle(this.getResources().getString(R.string.setting_modify_info));
        getUserProfile(NetWorkPath.GET_SETTING);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSave:
                String userId = SharedPreferencesUtil.getString(getApplicationContext(), SPKey.SP_USER_ID);
                postSettingProfile(NetWorkPath.POST_PROFILE_SAVE + "?id=" + userId);
                break;
        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    /**
     * 提交用户修改
     * @param urlString
     */
    private void postSettingProfile(String urlString) {
        String nickName = etNickName.getText().toString().trim();
        if("".equals(nickName) || nickName.length() == 0) {
            Toast.makeText(getApplicationContext(), "请输入昵称", Toast.LENGTH_LONG).show();
        }
        org.json.JSONObject obj = new org.json.JSONObject();
        org.json.JSONObject objSub = new org.json.JSONObject();
        try {
            objSub.put("name", nickName);
            obj.put("FeUserProfile", objSub);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), obj.toString());
        OkGo.<String>post(urlString)
                .headers("Authorization", GlobalConfig.AUTH_HEAD + MyApplication.getToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseData(response, 1);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    /**
     * 获取用户信息
     * @param urlString
     */
    public void getUserProfile(String urlString) {
        OkGo.<String>get(NetWorkPath.GET_SETTING)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //LogUtil.i(response.body().toString());
                        parseData(response, 2);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    /**
     * 解析保存返回结果
     * action=1表保存，action=2表获取
     * @param response
     * @param action
     */
    private void parseData(Response<String> response, int action) {
        if(response.isSuccessful()) {
            try {
                org.json.JSONObject obj = new org.json.JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(obj.getString("meta"));
                if(GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    if(action == 1) {
                        this.finish();
                        Toast.makeText(getApplicationContext(), objMeta.getString("msg"), Toast.LENGTH_SHORT).show();
                    } else if(action == 2) {
                        org.json.JSONArray dataArray = obj.getJSONArray("data");
                        org.json.JSONObject objSub = new org.json.JSONObject(dataArray.getJSONObject(0).getString("profile"));
                        etNickName.setText(objSub.getString("name"));
                    }
                } else {
                    Toast.makeText(getApplicationContext(), objMeta.getString("msg"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}
